package com.liqiye.paymanager.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.liqiye.paymanager.bean.payment.*;
import com.liqiye.paymanager.constant.PaymentPlatform;
import com.liqiye.paymanager.service.payment.PaymentService;
import com.liqiye.paymanager.service.payment.PaymentServiceFactory;
import com.liqiye.paymanager.service.payment.StripePaymentService;
import com.stripe.exception.StripeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * 支付接口
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentServiceFactory paymentServiceFactory;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public PaymentResponse create(@RequestBody PaymentRequest request) {
        PaymentService service = paymentServiceFactory.getService(request.getPlatform());
        return service.createPayment(request);
    }

    /**
     * 捕获订单（真正扣款）（PayPal独有的）
     * @param platform
     * @param orderId：这个是平台返回的订单id（例如请求Paypal创建一个订单返回的id）
     */
    @PostMapping("/capture")
    public CaptureResponse capture(@RequestParam("platform") PaymentPlatform platform,
                                   @RequestParam("orderId") String orderId) {
        PaymentService service = paymentServiceFactory.getService(platform);
        return service.captureOrder(orderId);
    }

    /**
     * 退款
     */
    @PostMapping("/refund")
    public RefundResponse refund(@RequestBody RefundRequest req) {
        PaymentService service = paymentServiceFactory.getService(req.getPlatform());
        return service.refund(req);
    }

    /**
     * 创建客户（Stripe独有的）
     * 如果是【重复付款】或者【订阅付款】这种类型的，必须基于 Customer 来付款
     * 创建 Customer --> 将 PaymentMethod 绑定到该 customer --> 创建订阅（Subscription）或用 customer 扣费
     */
    @PostMapping("/createCustomer")
    public ResponseEntity<CustomerResponse> createCustomer(@RequestBody CreateCustomerRequest req) {
        StripePaymentService service = SpringUtil.getBean(StripePaymentService.class);
        CustomerResponse customer = service.createCustomer(req);
        return ResponseEntity.ok(customer);
    }


    /**
     * 回调接口（例如在paypal的app管理页面配置的webhook，当paypal用户付款成功、退款成功、支付失败、取消、拒绝等，会触发这个接口）
     */
    @PostMapping("/callback")
    public ResponseEntity<CallbackResponse> callback(@RequestParam("platform") PaymentPlatform platform,
                                                     @RequestBody String body,
                                                     @RequestHeader("Signature") String signature) {
        PaymentService service = paymentServiceFactory.getService(platform);
        CallbackResponse response = service.handleCallback(body, signature);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/intent")
    @ResponseBody
    public Map<String, Object> createIntent(@RequestParam BigDecimal amount,
                                            @RequestParam String currency) throws StripeException {

        long amountInMinorUnit = amount.multiply(BigDecimal.valueOf(100)).longValue();

        PaymentRequest paymentRequest = new PaymentRequest();
        paymentRequest.setAmount(new BigDecimal(amountInMinorUnit));
        paymentRequest.setCurrency(currency);
        paymentRequest.setPaymentMethod("card");
        StripePaymentService service = SpringUtil.getBean(StripePaymentService.class);
        PaymentResponse resp = service.createPayment(paymentRequest);
        String clientSecret = resp.getClientSecret();
        Map<String, Object> response = new HashMap<>();
        response.put("clientSecret", clientSecret);
        return response;
    }

}
